package com.zyicoding.myfactory.service.impl;

import com.zyicoding.myfactory.dao.FactorymoneyMapper;
import com.zyicoding.myfactory.dao.GoodsinfoMapper;
import com.zyicoding.myfactory.pojo.Factorymoney;
import com.zyicoding.myfactory.pojo.Goodsinfo;
import com.zyicoding.myfactory.service.GoodsInfoService;
import com.zyicoding.myfactory.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class GoodsInfoServiceImpl implements GoodsInfoService {
    @Autowired
    private GoodsinfoMapper goodsinfoMapper;
    @Autowired
    private FactorymoneyMapper factorymoneyMapper;

    @Override
    public List<Goodsinfo> selectAllGoodsInfo() {
        return goodsinfoMapper.selectList(null);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public JsonResult buyGoods(int id, int count) {
        Goodsinfo goodsinfo = goodsinfoMapper.selectById(id);

        /*输入错误的id时*/
        if (goodsinfo == null) {
            return JsonResult.error("您购买的商品不存在！");
        }

        /*超过库存时*/
        if (goodsinfo.getCount() < count) {
            return JsonResult.error("购买数量超过库存，请刷新重试！");
        }

        /*工厂资金不足时*/
        Double needMoney = goodsinfo.getPrice() * count;
        Factorymoney factorymoney = factorymoneyMapper.selectList(null).get(0);
        Double haveMoney = factorymoney.getMoney();
        if (haveMoney < needMoney) {
            return JsonResult.error("您的工厂资金不足以支付该款项，请联系管理员充值！");
        }

        /*所有条件满足时*/
        goodsinfo.setCount(goodsinfo.getCount() - count);
        goodsinfoMapper.updateById(goodsinfo);

        factorymoney.setMoney(factorymoney.getMoney() - needMoney);
        factorymoneyMapper.update(factorymoney,null);
        return JsonResult.ok("购买成功！");
    }
}
